<template>
	<view class="content">
		<!-- <nav-header /> -->
		<view class="tab-card flex-row-start" :style="{top: `${getTop()}`}">
			<view class="tab-item" :class="{'tab-item-active': tabId == 1}" @click="setTabId(1)">未完成</view>
			<view class="tab-item" :class="{'tab-item-active': tabId == 2}" @click="setTabId(2)">已完成</view>
		</view>
		<view class="list-card-wrap" style="margin-top: 96rpx;">
			<view v-for="(item,index) in tableData" :key="index" class="list-card" @click="toPage(item)">
				<view class="flex-row-between">
					<view @click.stop="toDetail(item)" class="flex-row">
						<text class="gray-text">任务编号</text>
						<text class="black-text-34" style="margin-left: 20rpx;">{{item.no}}</text>
						<uni-icons type="right" size="16" color="#8997A8"></uni-icons>
					</view>
					<view class="tag">{{item.storehouseLocationNo}}</view>
				</view>
				<view class="content flex-row">
					<view class="flex-column flex1">
						<text class="gray-text">物料编号</text>
						<text class="black-text">{{item.productNo}}</text>
					</view>
					<view class="split"></view>
					<view class="flex-column flex1">
						<text class="gray-text">物料名称</text>
						<text class="black-text">{{item.productName}}</text>
					</view>
				</view>
				<view v-if="tabId == 1" class="flex-row-between">
					<text class="gray-text">{{'创建时间' +  item.createTime}}</text>
					<view class="flex-row">
						<navigator :url="'/pages/quality/iqc/edit?id=' + item.id" hover-class="other-navigator-hover">
						  <view class="botton">检验</view>
						</navigator>
						<view @click="finishTask(item.id,item.no,item)" class="botton p-botton">完成</view>
					</view>
				</view> 
				<view v-if="tabId == 2" class="">
					<view class="flex-row-between">
						<text class="gray-text">创建时间</text>
						<text class="gray-text">{{item.createTime}}</text>
					</view>
					<view class="flex-row-between">
						<text class="gray-text">完成时间</text>
						<text class="gray-text">{{item.finishTime}}</text>
					</view>
				</view>
			</view>
		</view>
		
		<uni-popup ref="popup" type="bottom">底部弹出 Popup</uni-popup>
		
		<popup ref="inputDialog" @beforeClosed="" @handleCheck="finishTaskHasProcessMode">
			<view class="">
				<view class="flex-row-start"><text class="gray-text font-30" style="width:150rpx">检验结果：</text><text class="q-tag q-tag-red font-34">NG</text></view>
				<view class="flex-row-start" style="margin-top: 16rpx;">
					<text class="gray-text font-30" style="width:150rpx">处理方式：</text>
					<picker @change="(arr)=>bindPickerActualValue(arr,item)" :value="processMode.value" :range="processModeList" range-key="label">
						<view class="black-text font-34" style="height:50rpx">{{processMode&&processMode.label?processMode.label:'请选择处理方式'}}</view>
					</picker>
				</view>
				<view v-if="processMode.value == '2'" class="flex-row-start" style="margin-top: 16rpx;">
					<text class="gray-text font-30" style="width:150rpx">退货数量：</text>
					<input type="number" v-model="returnQuantity" @input="setNum" class="black-text font-34 flex1" placeholder="请输入退货数量" />
				</view>
			</view>
		</popup>
	</view>
</template>

<script>
	import { getTop } from '@/utils/common.js'
	import {
		qualityMainTaskList,
		getInStockBatchInfo,
		inoutstock,
		saveDetailData,
		getTaskNgNum,
		completeTask
	} from "./api"
	export default {
		data() {
			return {
				getTop,
				// 遮罩层
				loading: true,
				// 查询参数
				queryParams: {
					pageNum: 1,
					pageSize: 10,
				},
				total: 0,
				searchValue:'',
				tabId:1,
				taskId:'',
				taskNo:'',
				taskInfo:{},
				returnQuantity:'',
				tableData:[],
				processModeList:[
					{
						value:'1',
						label:'让步接收'
					},
					{
						value:'2',
						label:'部分接收'
					},
					{
						value:'3',
						label:'退货'
					}],
				processMode:{
					value:'1',
					label:'让步接收'
				},
				qualityType:''
			}
		},
		onNavigationBarSearchInputChanged(obj){
			if(!obj.text){
				this.queryParams.no = '';
				this.refreshList()
			}
		},
		onNavigationBarSearchInputConfirmed(obj) {
			// obj.text
			this.queryParams.no = obj.text;
			this.refreshList()
		},
		// 上拉加载
		onReachBottom() {
			if (this.tableData.length >= this.total) {
				return;
			}
			this.queryParams.pageNum++;
			this.getIqcList();
		},
		onLoad(option) {
			let that = this
			uni.$on('refreshList',function(data){
				that.refreshList()
			})
			this.qualityType = option.qualityType
		},
		onUnload(){
			uni.$off('refreshList')
		},
		created() {
			this.getIqcList();
		},
		methods: {
			refreshList(){
				this.tableData = [];
				this.total = 0;
				this.queryParams.pageNum = 1;
				this.getIqcList();
			},
			getIqcList(){
				uni.showLoading({
					title: '加载中...'
				});
				let searchFinish = 'N';
				if(this.tabId == 2){
					searchFinish = 'Y';
				}
				qualityMainTaskList({
					qualityType:this.qualityType,//'IQC',
					searchFinish:searchFinish,
					no:this.queryParams.no,
					page:this.queryParams.pageNum,
					size:this.queryParams.pageSize
				}).then(res => {
					if (res.code == 200) {
						this.tableData = this.tableData.concat(res.rows);
						this.total = res.total;
						uni.hideLoading();
					}
				})
			},
			toPage(item){
				if(this.tabId == 2){
					this.toDetail(item);
				}
			},
			toDetail(item){
				this.$tab.navigateTo("/pages/quality/iqc/detail?id=" + item.id);
			},
			setTabId(tabId){
				this.tabId = tabId
				this.refreshList();
			},
			clearForm(){
				this.form = {
					batchNo: '',
					storehouseLocationNo: '',
					productNo: '',
					productName: '',
					quantity: ''
				}
			},
			// 验证大于等于1的整数
			setNum(e) {
				if (e.target.value) {
					let newValue = e.target.value.replace(/^\D*(\d*).*$/g, "$1")
					newValue = Math.max(1, newValue)
					this.$nextTick(() => {
						this.form.quantity = newValue
					})
				}
			},
			getInStockBatchInfo(e) {
				if (e.target.value === "") {
					this.$modal.msg("请输入批次号")
					this.clearForm()
				}else{
					getInStockBatchInfo(e.target.value).then(res => {
						if (res.code == 200) {
							this.form = res.data
						}
					})
				}
			},
			submit() {
				if (!this.form.batchNo ) {
					this.$modal.msg("请输入批次号")
				} else if (!this.form.storehouseLocationNo ) {
					this.$modal.msg("请输入库位编码")
				} else if (!this.form.quantity  || this.form.quantity == 0) {
					this.$modal.msg("请输入数量")
				} else {
					this.$modal.loading("入库中...")
					inoutstock({...this.form, type:0, operation:0}).then(res => {
						this.$modal.closeLoading()
						if (res.code == 200) {
							this.clearForm()
							this.$modal.msgSuccess("入库成功")
						} else {
							res.msg && this.$modal.confirmClose(res.msg)
						}
					})
				}
			},
			// 完成任务
			finishTask(id,no,item){
				this.$modal.confirm('是否确认完成任务').then(() => {
					this.$set(this,'taskId',id);
					this.$set(this,'taskNo',no);
					this.$set(this,'taskInfo',item);
					this.$modal.loading("加载中...")
					// 调用接口判断是否全部质检明细都为合格
					getTaskNgNum({
						taskNo:no
					}).then(resNgNum => {
						this.$modal.closeLoading()
						if (resNgNum.code == 200) {
							// 如果不合格质检项数量大于0，需要弹窗选择处理方式
							if(resNgNum.data > 0){
								this.$refs.inputDialog.open()
							}
							// 如果全部合格，调用接口完成质检任务
							else{
								completeTask({
									id:id,
									qualityResult:"OK"
								}).then(completeRes => {
									if(completeRes.code == 200){
										// 刷新数据
										this.$modal.msgSuccess("操作成功");
										setTimeout(()=> {
											this.refreshList();
										}, 1000);
									} else {
										resNgNum.msg && this.$modal.confirmClose(resNgNum.msg)
									}
								})
							}
						} else {
							resNgNum.msg && this.$modal.confirmClose(resNgNum.msg)
						}
					})
				})
			},
			bindPickerActualValue(e){
				this.processMode = this.processModeList[e.detail.value]
			},
			setNum(e){
				this.$set(this,'returnQuantity',validNum(e))
			},
			// 完成任务（弹窗后确认，带处理方式）
			finishTaskHasProcessMode(){
				if(this.processMode.value == '2'){
					if(!this.returnQuantity){
						this.$modal.msg("请输入退货数量");
						return
					}
					if(this.returnQuantity > this.taskInfo.totalQuantity){
						this.$modal.msg("退货数量不能大于检测数量");
						return
					}
				}
				completeTask({
					id:this.taskId,
					qualityResult:"NG",
					processMode:this.processMode.value,
					returnQuantity:this.returnQuantity
				}).then(completeRes => {
					if(completeRes.code == 200){
						this.$refs.inputDialog.closed();
						// 刷新数据
						this.$modal.msgSuccess("操作成功");
						setTimeout(()=> {
						this.refreshList();
						}, 1000);
					
					}else{
						this.$modal.msgError(completeRes.msg);
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #F8F8F8;
	}
</style>
<style lang="scss" scoped>
	.content{
		// margin: 17rpx 25rpx;
	}
</style>
